package com.ybkj.o2o.zhuanche.manager.impl;

import com.ybkj.o2o.zhuanche.common.DataGrid;
import com.ybkj.o2o.zhuanche.common.query.CarTypeCompanyQuery;
import com.ybkj.o2o.zhuanche.common.query.CarTypeQuery;
import com.ybkj.o2o.zhuanche.entity.CarType;
import com.ybkj.o2o.zhuanche.entity.CarTypeCompany;
import com.ybkj.o2o.zhuanche.entity.CarTypeDetail;
import com.ybkj.o2o.zhuanche.entity.CarTypeRel;
import com.ybkj.o2o.zhuanche.entity.ServiceType;
import com.ybkj.o2o.zhuanche.manager.CarTypeManager;
import com.ybkj.o2o.zhuanche.service.CarService;
import com.ybkj.o2o.zhuanche.service.CarTypeCompanyService;
import com.ybkj.o2o.zhuanche.service.CarTypeDetailService;
import com.ybkj.o2o.zhuanche.service.CarTypeService;
import com.ybkj.o2o.zhuanche.service.ServiceTypeService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DefaultCarTypeManager implements CarTypeManager {

  @Autowired
  private CarTypeService carTypeService;
  @Autowired
  private ServiceTypeService serviceTypeService;
  @Autowired
  private CarTypeCompanyService carTypeCompanyService;
  @Autowired
  private CarService carService;
  @Autowired
  private CarTypeDetailService carTypeDetailService;

  @Override
  public List<CarType> findAll(Long companyId, String appKey) {

    return carTypeService.findAll(companyId, appKey);

  }

  @Override
  public CarType findByCarTypeId(Long carTypeId, String appKey) {

    return carTypeService.findByCarTypeId(carTypeId, appKey);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public CarType save(CarType carType) {
    int effect = carTypeService.insert(carType);
    CarTypeDetail carTypeDetail = new CarTypeDetail();
    carTypeDetail.setAppKey(carType.getAppKey());
    carTypeDetail.setCarTypeId(carType.getId());
    carTypeDetail.setCarTypeName(carType.getTypeName());
    carTypeDetail.setMiliagePrice("1");
    carTypeDetail.setStartPrice("1");
    carTypeDetail.setTimePrice("1");
    carTypeDetail.setPriceDetail("￥ 1起租价 + ￥ 1 / 分钟 + ￥ 1 / 公里");
    
    //保存车型详情记录
    carTypeDetailService.insertCarTypeDetail(carTypeDetail);
    
    if (effect != 1) {
      throw new RuntimeException("汽车类型创建失败");
    }
    return carType;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void update(CarType carType) {
    carTypeService.updateIngoreNull(carType);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void deleteById(Long id, String appKey) {
    carService.updateCarTypeId(id, appKey);
    carTypeService.deleteById(id, appKey);
  }

  @Override
  public DataGrid<CarType> findByParams(CarTypeQuery carTypeQuery) {

    List<CarType> list = carTypeService.findByParams(carTypeQuery);

    Long count = carTypeService.countByParams(carTypeQuery);

    DataGrid<CarType> dataGrid = new DataGrid<>();
    dataGrid.setRows(list);
    dataGrid.setTotal(count);

    return dataGrid;
  }

  @Override
  public List<CarType> findByParam(CarTypeQuery carTypeQuery) {
    return carTypeService.findByParams(carTypeQuery);
  }

  @Override
  public Long countByParams(CarTypeQuery carTypeQuery) {
    return carTypeService.countByParams(carTypeQuery);
  }

  @Override
  public List<Map<String, Object>> queryCarTypes(Long companyId, String appKey) {
    List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
    CarTypeCompanyQuery carTypeCompanyQuery = new CarTypeCompanyQuery();
    carTypeCompanyQuery.setCompanyId(companyId);
    carTypeCompanyQuery.setAppKey(appKey);
    List<CarTypeCompany> carTypeCompanyList =
        carTypeCompanyService.findByCompanyIdAndCarTypeId(carTypeCompanyQuery);
    if (carTypeCompanyList != null && carTypeCompanyList.size() != 0) {
      boolean ifTaxi = true;
      for (CarTypeCompany carTypeCompany : carTypeCompanyList) {
        CarType carType = carTypeService.findByCarTypeId(carTypeCompany.getCarTypeId(), appKey);

        if (null != carType) {
          if (StringUtils.isNotBlank(carType.getIfTaxi())) {
            if ("1".equals(carType.getIfTaxi())) { // 是出租车的专车类型
              if (ifTaxi) {
                Map<String, Object> map = new HashMap<String, Object>();

                List<Map<String, Object>> serverTypes = new ArrayList<Map<String, Object>>();

                List<ServiceType> serverTypeList =
                    serviceTypeService.findByCarTypeIdAndCarTypeCompanyId(carType.getId(),
                        carTypeCompany.getId(), appKey);
                if (!CollectionUtils.isEmpty(serverTypeList)) {
                  for (ServiceType serverType : serverTypeList) {
                    Map<String, Object> st = new HashMap<String, Object>();
                    st.put("typeId", serverType.getId());
                    st.put("typeName", serverType.getTypeName());
                    st.put("name", serverType.getName());
                    st.put("priceId", serverType.getAreaId());
                    serverTypes.add(st);
                  }
                  map.put("typeName", "出租车");
                  map.put("typeId", carType.getId());
                  map.put("photo", carType.getPhoto());
                  map.put("serverTypes", serverTypes);
                  listMap.add(map);
                  ifTaxi = false;
                }
              }
            } else {

              Map<String, Object> map = new HashMap<String, Object>();

              List<Map<String, Object>> serverTypes = new ArrayList<Map<String, Object>>();

              List<ServiceType> serverTypeList =
                  serviceTypeService.findByCarTypeIdAndCarTypeCompanyId(carType.getId(),
                      carTypeCompany.getId(), appKey);
              if (!CollectionUtils.isEmpty(serverTypeList)) {
                for (ServiceType serverType : serverTypeList) {
                  Map<String, Object> st = new HashMap<String, Object>();
                  st.put("typeId", serverType.getId());
                  st.put("typeName", serverType.getTypeName());
                  st.put("name", serverType.getName());
                  st.put("priceId", serverType.getAreaId());
                  serverTypes.add(st);
                }
                map.put("typeName", carType.getTypeName());
                map.put("typeId", carType.getId());
                map.put("photo", carType.getPhoto());
                map.put("serverTypes", serverTypes);
                listMap.add(map);
              }

            }
          } else {
            Map<String, Object> map = new HashMap<String, Object>();

            List<Map<String, Object>> serverTypes = new ArrayList<Map<String, Object>>();

            List<ServiceType> serverTypeList =
                serviceTypeService.findByCarTypeIdAndCarTypeCompanyId(carType.getId(),
                    carTypeCompany.getId(), appKey);

            if (!CollectionUtils.isEmpty(serverTypeList)) {

              for (ServiceType serverType : serverTypeList) {
                Map<String, Object> st = new HashMap<String, Object>();
                st.put("typeId", serverType.getId());
                st.put("typeName", serverType.getTypeName());
                st.put("name", serverType.getName());
                st.put("priceId", serverType.getAreaId());
                serverTypes.add(st);
              }
              map.put("typeName", carType.getTypeName());
              map.put("typeId", carType.getId());
              map.put("photo", carType.getPhoto());
              map.put("serverTypes", serverTypes);
              listMap.add(map);
            }

          }
        }
      }
    }
    return listMap;
  }

  @Override
  public List<CarType> queryCarTypesV4up(Long companyId, String appKey) {
    CarTypeQuery carTypeQuery = new CarTypeQuery();
    carTypeQuery.setAppKey(appKey);
    carTypeQuery.setCompanyId(companyId);

    return carTypeService.queryCarTypeV4up(carTypeQuery);
  }

  @Override
  public CarType saveCarType(CarType carType, Long tangzuAreaId, Long rizuAreaId,
      Long banrizuAreaId, Long jiejiAreaId, Long songjiAreaId, Long jiezhanAreaId,
      Long songzhanAreaId, String tangzuAreaName, String rizuAreaName, String banrizuAreaName,
      String jiejiAreaName, String songjiAreaName, String jiezhanAreaName, String songzhanAreaName,
      String appKey) {

    carTypeService.insert(carType);

    Long carTypeId = carType.getId();
    if (tangzuAreaId != null && tangzuAreaId != 0) {
      ServiceType serverType = new ServiceType();
      serverType.setAreaId(tangzuAreaId);
      serverType.setAreaName(tangzuAreaName);
      serverType.setCarTypeId(carTypeId);
      serverType.setName(com.ybkj.o2o.zhuanche.entity.Order.ServiceType.tangzu.name());
      serverType.setTypeName("趟租");
      serverType.setAppKey(appKey);
      serviceTypeService.insert(serverType);
    }
    if (rizuAreaId != null && rizuAreaId != 0) {
      ServiceType serverType = new ServiceType();
      serverType.setAreaId(rizuAreaId);
      serverType.setAreaName(rizuAreaName);
      serverType.setCarTypeId(carTypeId);
      serverType.setName(com.ybkj.o2o.zhuanche.entity.Order.ServiceType.rizu.name());
      serverType.setTypeName("日租");
      serverType.setAppKey(appKey);
      serviceTypeService.insert(serverType);
    }
    if (banrizuAreaId != null && banrizuAreaId != 0) {
      ServiceType serverType = new ServiceType();
      serverType.setAreaId(banrizuAreaId);
      serverType.setAreaName(banrizuAreaName);
      serverType.setCarTypeId(carTypeId);
      serverType.setName(com.ybkj.o2o.zhuanche.entity.Order.ServiceType.banrizu.name());
      serverType.setTypeName("半日租");
      serverType.setAppKey(appKey);
      serviceTypeService.insert(serverType);
    }
    if (jiejiAreaId != null && jiejiAreaId != 0) {
      ServiceType serverType = new ServiceType();
      serverType.setAreaId(jiejiAreaId);
      serverType.setAreaName(jiejiAreaName);
      serverType.setCarTypeId(carTypeId);
      serverType.setName(com.ybkj.o2o.zhuanche.entity.Order.ServiceType.jieji.name());
      serverType.setTypeName("接机");
      serverType.setAppKey(appKey);
      serviceTypeService.insert(serverType);
    }
    if (songjiAreaId != null && songjiAreaId != 0) {
      ServiceType serverType = new ServiceType();
      serverType.setAreaId(songjiAreaId);
      serverType.setAreaName(songjiAreaName);
      serverType.setCarTypeId(carTypeId);
      serverType.setName(com.ybkj.o2o.zhuanche.entity.Order.ServiceType.songji.name());
      serverType.setTypeName("送机");
      serverType.setAppKey(appKey);
      serviceTypeService.insert(serverType);
    }
    if (jiezhanAreaId != null && jiezhanAreaId != 0) {
      ServiceType serverType = new ServiceType();
      serverType.setAreaId(jiezhanAreaId);
      serverType.setAreaName(jiezhanAreaName);
      serverType.setCarTypeId(carTypeId);
      serverType.setName(com.ybkj.o2o.zhuanche.entity.Order.ServiceType.jiezhan.name());
      serverType.setTypeName("接站");
      serverType.setAppKey(appKey);
      serviceTypeService.insert(serverType);
    }
    if (songzhanAreaId != null && songzhanAreaId != 0) {
      ServiceType serverType = new ServiceType();
      serverType.setAreaId(songzhanAreaId);
      serverType.setAreaName(songzhanAreaName);
      serverType.setCarTypeId(carTypeId);
      serverType.setName(com.ybkj.o2o.zhuanche.entity.Order.ServiceType.songzhan.name());
      serverType.setTypeName("送站");
      serverType.setAppKey(appKey);
      serviceTypeService.insert(serverType);
    }

    return carType;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void deleteCarType(Long carTypeId, String appKey) {
    carService.updateCarTypeId(carTypeId, appKey);

    carTypeService.deleteById(carTypeId, appKey);// 删除车型

    carTypeCompanyService.deleteByCarTypeId(carTypeId, appKey); // 删除车型关联的公司

    serviceTypeService.deleteByCarTypeId(carTypeId, appKey); // 删除车型关联的公司下的收费标准

    carTypeService.deleteRel(carTypeId, appKey);// 删除可选类型关联信息
    
    carTypeDetailService.deleteByCarTypeId(carTypeId, appKey); //删除车型详情(车费,图片详情)信息
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public CarType updateCarType(Long carTypeId, String typeName, Integer sequence, String picture,
      String appKey, String ifTaxi, String accessibleType) {
    CarType carType = carTypeService.findByCarTypeId(carTypeId, appKey);

    CarTypeCompanyQuery carTypeCompanyQuery = new CarTypeCompanyQuery();
    carTypeCompanyQuery.setCarTypeId(carTypeId);
    carTypeCompanyQuery.setAppKey(appKey);
    if (!carType.getSequence().equals(sequence)) {
      carType.setSequence(sequence);
      List<CarTypeCompany> list =
          carTypeCompanyService.findByCompanyIdAndCarTypeId(carTypeCompanyQuery);
      for (CarTypeCompany carTypeCompany : list) {
        if (sequence.equals(carTypeCompany.getSequence())) {
          break;
        }
        carTypeCompany.setSequence(sequence);
        carTypeCompanyService.update(carTypeCompany);
      }
    }
    carType.setTypeName(typeName);
    if (StringUtils.isNotBlank(picture)) {
      try {
        int index =
            Integer.parseInt(picture.substring(picture.lastIndexOf("picture"))
                .replace("picture", "").replace(".png", ""));
        String photo =
            "/assets/img/zhuanchecartype/xuanzhong" + index + ".png"
                + ",/assets/img/zhuanchecartype/weixuan" + index + ".png";
        carType.setPicture(picture);
        carType.setPhoto(photo);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
    carType.setIfTaxi(ifTaxi);
    carType.setAccessibleType(accessibleType);
    carTypeService.updateIngoreNull(carType);
    // 删除之前的关联信息
    carTypeService.deleteRel(carTypeId, appKey);
    String accessible[];
    CarTypeRel carTypeRel = new CarTypeRel();
    if (StringUtils.isNotBlank(accessibleType)) {
      accessible = accessibleType.split(",");
      for (int i = 0; i < accessible.length; i++) {
        // 循环组装保存类型关联信息
        carTypeRel.setCarTypeId(carType.getId());
        carTypeRel.setAccessibleType(accessible[i]);
        carTypeRel.setAppKey(appKey);
        carTypeService.insertCarTypeRel(carTypeRel);
      }
    }
    return carType;
  }

  @Override
  public List<Map<String, Object>> findByCarTypeIdV4up(Long carTypeId, Long companyId, String appKey) {
    List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
    CarTypeCompanyQuery carTypeCompanyQuery = new CarTypeCompanyQuery();
    carTypeCompanyQuery.setCompanyId(companyId);
    carTypeCompanyQuery.setCarTypeId(carTypeId);
    carTypeCompanyQuery.setAppKey(appKey);
    List<CarTypeCompany> carTypeCompanyList =
        carTypeCompanyService.findByCompanyIdAndCarTypeId(carTypeCompanyQuery);
    if (carTypeCompanyList != null && carTypeCompanyList.size() != 0) {
      CarTypeCompany typeCompany = carTypeCompanyList.get(0);
      List<ServiceType> serverTypeList =
          serviceTypeService.findByCarTypeCompanyId(typeCompany.getId(), appKey);
      for (ServiceType serverType : serverTypeList) {
        Map<String, Object> st = new HashMap<String, Object>();
        st.put("typeId", serverType.getId());
        st.put("typeName", serverType.getTypeName());
        st.put("priceId", serverType.getAreaId());
        st.put("carTypeId",serverType.getCarTypeId());
        listMap.add(st);
      }
    }
    return listMap;

  }

  @Override
  public DataGrid<CarType> queryCarTypeV4up(CarTypeQuery carTypeQuery) {

    DataGrid<CarType> dataGrid = new DataGrid<CarType>();
    List<CarType> list = carTypeService.findByParams(carTypeQuery);
    if (null != list && list.size() > 0) {
      for (int i = 0; i < list.size(); i++) {
        List<CarTypeRel> carTypeRelList =
            carTypeService.getCarTypeRel(list.get(i).getId(), list.get(i).getAppKey());
        String accessibleType = "";
        if (null != carTypeRelList && carTypeRelList.size() > 0) {
          for (int j = 0; j < carTypeRelList.size(); j++) {
            if (j < carTypeRelList.size() - 1) {
              accessibleType += carTypeRelList.get(j).getAccessibleType() + ",";
            } else {
              accessibleType += carTypeRelList.get(j).getAccessibleType();
            }
          }
        }
        if (!accessibleType.equals("")) {
          list.get(i).setAccessibleType(accessibleType.toString());
        }
      }
    }
    Long total = carTypeService.countByParams(carTypeQuery);
    dataGrid.setRows(list);
    dataGrid.setTotal(total);
    return dataGrid;

  }

  @Override
  public Long countByCompanyIdV4up(Long companyId, String companyName, String appKey) {

    return carTypeService.countByCompanyIdV4up(companyId, companyName, appKey);
  }

  @Override
  public Long countByCompanyName(CarTypeQuery carTypeQuery) {
    Long total = carTypeService.countByParams(carTypeQuery);
    return total;
  }

  @Override
  public ServiceType queryServiceType(CarTypeQuery carTypeQuery) {
    return serviceTypeService.queryServiceType(carTypeQuery);
  }

  @Override
  public Long queryServiceTypeById(Long typeId, String appKey) {
    ServiceType type = serviceTypeService.findByServiceTypeId(typeId, appKey);
    if (null != type && type.getAreaId() != null) {
      return type.getAreaId();
    } else {
      return null;
    }
  }

  @Override
  public List<CarType> findByAreaId(Long areaId, String appKey) {

    return carTypeService.findByAreaId(areaId, appKey);
  }

  @Override
  public void saveCarTypeRel(CarTypeRel carTypeRel) {
    int effect = carTypeService.insertCarTypeRel(carTypeRel);
    if (effect != 1) {
      throw new RuntimeException("汽车类型创建失败");
    }
  }

  @Override
  public List<CarTypeRel> findByCarTypeRelBycarTypeId(Long carTypeId, String appKey) {
    return carTypeService.getCarTypeRel(carTypeId, appKey);
  }

  @Override
  public List<CarType> getCarTypeByIftaxi(String ifTaxi, String appKey) {
    return carTypeService.getCarTypeByIftaxi(ifTaxi, appKey);
  }

  @Override
  public List<CarTypeDetail> queryCarTypeDetail(String appKey) {
    return carTypeDetailService.findAll(appKey);
  }
  @Override
  public void initCarTypeDetail(String appKey) {
    
    CarTypeQuery carTypeQuery= new CarTypeQuery();
    carTypeQuery.setAppKey(appKey);
    List<CarType> list = carTypeService.findByParams(carTypeQuery);
    if (!CollectionUtils.isEmpty(list)) {
      carTypeDetailService.clear(appKey);
      for (CarType carType : list) {
        CarTypeDetail carTypeDetail = new CarTypeDetail();
        carTypeDetail.setAppKey(appKey);
        carTypeDetail.setCarTypeId(carType.getId());
        carTypeDetail.setCarTypeName(carType.getTypeName());
        carTypeDetail.setMiliagePrice("1");
        carTypeDetail.setStartPrice("1");
        carTypeDetail.setTimePrice("1");
        carTypeDetail.setPriceDetail("￥ 1起租价 + ￥ 1 / 分钟 + ￥ 1 / 公里");
        carTypeDetailService.insertCarTypeDetail(carTypeDetail );
      }
    }
  }
  
  @Override
  public int updateCarTypeDetail(Long id,String photo,String priceDetail,
      String startPrice,String timePrice,String miliagePrice,String appKey) {
    return carTypeDetailService.updateCarTypeDetail(id,photo,priceDetail, startPrice,timePrice, miliagePrice, appKey);
  }

}
